package com.mai4j.maiadmin.support.i18n;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Locale;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 * <p>
 * 模板中使用 #(i18n['key']) 来获取国际化的值，所以需要继承Map
 *
 * @author xiyoufang
 */
@Component
public class I18n extends HashMap<String, String> {
    /**
     * messageSource
     */
    private final MessageSource messageSource;

    public I18n(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public static Locale getLocale() {
        return LocaleContextHolder.getLocale();
    }

    public static String getTag() {
        return getLocale().toLanguageTag();
    }

    @Override
    public String get(Object key) {
        return get(key, new Object[]{});
    }

    public String get(Object key, Object... args) {
        return messageSource.getMessage((String) key, args, getLocale());
    }

    /**
     * @param key  key
     * @param tag  tag
     * @param args args
     * @return String
     */
    public String getByTag(Object key, String tag, Object... args) {
        return messageSource.getMessage((String) key, args, Locale.forLanguageTag(tag));
    }

}
